<template>
  <div id="container">
    <el-autocomplete
      class="inline-input"
      v-model="keyword"
      :fetch-suggestions="querySearch"
      placeholder="请输入内容"
      @select="handleSelect"
      :trigger-on-focus="false"
    ></el-autocomplete>
    <div id="map"></div>
  </div>
</template>

<script setup>
import axios from "axios";

const props = defineProps({
  lat: {
    default: "",
  },
  lnt: {
    default: "",
  },
});

const emit = defineEmits();

const keyword = ref("");
const map = ref(null);
const restaurants = ref([]);
const markerArray = ref([]);

async function querySearch(queryString, cb) {
  const key = "YT2BZ-V6MW3-YU33F-OH7AK-RQN67-IGFCM";
  const url = `https://apis.map.qq.com/ws/place/v1/suggestion/?keyword=${queryString}&key=${key}&output=jsonp&callback=jsonpCallback`;

  // 动态创建一个 script 标签
  const script = document.createElement("script");
  script.src = url;
  document.body.appendChild(script);

  // 全局定义 JSONP 回调函数
  window.jsonpCallback = function (response) {
    console.log("搜索结果", response);
    const suggestions = response.data.map((item) => ({
      value: item.title,
      address: item.address,
      lat: item.location.lat,
      lng: item.location.lng,
      location: item.location,
    }));
    cb(suggestions);
    restaurants.value = suggestions;
    // 清理 script 标签
    document.body.removeChild(script);
  };
}

function handleSelect(item) {
  renderMarker([item]);
}
// 渲染marker
function renderMarker(markersData) {
  map.value.setCenter(
    new qq.maps.LatLng(markersData[0].lat, markersData[0].lng)
  );
  markersData.forEach((i) => {
    (function (n) {
      var marker = new qq.maps.Marker({
        map: map.value,
        position: new qq.maps.LatLng(i.lat * 1, i.lng * 1),
        title: i.value,
      });

      markerArray.value.push(marker);
      /**
       * marker点击事件
       */
      qq.maps.event.addListener(marker, "click", function () {
        /**
         * @type {boolean}
         */
        emit("getPosition", marker.position);
      });
    })(i);
  });
}

function init() {
  if (props.lat && props.lnt) {
    map.value = new qq.maps.Map(document.getElementById("map"), {
      center: new qq.maps.LatLng(props.lat, props.lnt),
      zoom: 12,
    });
  } else {
    map.value = new qq.maps.Map(document.getElementById("map"), {
      center: new qq.maps.LatLng(34.34457, 108.943176),
      zoom: 12,
    });
  }
}

onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
#container {
  width: 100%;
  height: 600px;

  #map {
    width: 100%;
    height: 550px;
    margin-top: 20px;
  }
}
</style>
